package model

import (
	"crypto/md5"
	"encoding/hex"
	"errors"
	"gorm.io/gorm"
	"time"
)

type (
	UserDaoModel interface {
		Insert(user User) (err error)
		SelectByAccount(account string) (User, error, int64)
		UpdateNameAndSex(account string, name string, sex int) error
		DelSoft(id int) (err error)
		Del(id int) (err error)
		GetId(account string) int
		UpdateDepth(id int, depth int) error
	}
	//DefaultUserDao 用来实现接口的结构体
	DefaultUserDao struct {
		conn  *gorm.DB
		table string
	}
	// User 这里定义一个user方式循环调用
	User struct {
		Id           int       `json:"id"`
		Name         string    `json:"name"`
		Account      string    `json:"account"`
		Password     string    `json:"password"`
		Sex          int       `json:"sex"`
		CompanyName  string    `json:"company_name"`
		VipLevel     int       `json:"vip_level"`
		Productivity int       `json:"productivity"`
		Depth        int       `json:"depth"`
		Power        int       `json:"power"`
		DigRate      int       `json:"dig_rate"`
		CreateTime   time.Time `json:"create_time"`
		DeleteTime   time.Time `json:"delete_time"`
		DelState     int       `json:"del_state"`
	}
)

func NewDefaultUserDao(conn *gorm.DB) *DefaultUserDao {
	return &DefaultUserDao{
		conn:  conn,
		table: "user",
	}
}

// Insert 插入新角色
func (u *DefaultUserDao) Insert(user User) (err error) {
	user.CreateTime = time.Now()
	user.DeleteTime = time.Unix(0, 0)
	//存入时使用 md5加密
	hasher := md5.New()
	hasher.Write([]byte(user.Password))
	hashedPassword := hasher.Sum(nil)
	user.Password = hex.EncodeToString(hashedPassword)
	u.conn.Create(&user)
	return err
}

// SelectByAccount 根据账号名称返回整个账号
func (u *DefaultUserDao) SelectByAccount(account string) (User, error, int64) {
	var user User
	var count int64
	var err error
	u.conn.Model(&user).Where("account = ?", account).Count(&count)
	if count == 0 {
		err = errors.New("账号不存在")
		return User{}, err, 0
	}
	if user.DelState == 1 {
		err = errors.New("账号不存在")
		return User{}, err, 0
	}
	u.conn.Where("account = ?", account).First(&user)
	return user, nil, count
}

// UpdateNameAndSex 更新用户的姓名性别信息
func (u *DefaultUserDao) UpdateNameAndSex(account string, name string, sex int) error {

	err := u.conn.Model(&User{}).Where("account = ?", account).Updates(map[string]interface{}{
		"name": name,
		"sex":  sex,
	}).Error

	return err
}

// DelSoft 软删除用户信息
func (u *DefaultUserDao) DelSoft(id int) error {
	err := u.conn.Model(&User{}).Where("id = ?", id).Updates(map[string]interface{}{
		"del_state": 1,
		"del_time":  time.Now().Unix(),
	}).Error

	return err
}

// Del 删除用户信息
func (u *DefaultUserDao) Del(id int) error {
	res := u.conn.Model(&User{}).Where("id = ?", id).Delete(&User{})
	return res.Error
}

func (u *DefaultUserDao) GetId(account string) int {
	var user User
	u.conn.Model(&user).Where("account = ?", account).First(&user)
	return user.Id
}

func (u *DefaultUserDao) UpdateDepth(id int, depth int) error {
	res := u.conn.Model(&User{}).Where("id=?", id).Update("depth", depth)
	return res.Error
}
